package com.xchb.im.conne.server.netty;

import io.netty.channel.Channel;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollServerSocketChannel;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class WSServer {

	
	private EventLoopGroup mainGroup;
	private EventLoopGroup subGroup;
	private ServerBootstrap server;
	private Channel channel;

	private static class SingletionWSServer{
		static final WSServer instance = new WSServer();
	}


	public static WSServer getInstance() {
		return SingletionWSServer.instance;
	}
	
	private WSServer() {
		mainGroup = new NioEventLoopGroup();
		subGroup = new NioEventLoopGroup();
		server = new ServerBootstrap();
		server.group(mainGroup, subGroup)
			.channel(Epoll.isAvailable()?EpollServerSocketChannel.class:NioServerSocketChannel.class)
			.childHandler(new WSServerInitialzer());
	}
	
	public void start(int port) {
		try {
			this.channel = server.bind(port).sync().channel();
		} catch (InterruptedException e) {
			e.printStackTrace();
			if(mainGroup!=null){
				mainGroup.shutdownGracefully();
			}
			if(subGroup!=null){
				subGroup.shutdownGracefully();
			}
		}
	}
}
